package web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import pojo.Brand;
import pojo.pageBean;
import service.brandService.brandService;
import service.brandServiceImpl.brandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet("/selectByPageConditionServlet")
public class selectByPageConditionServlet extends HttpServlet {
    private brandService brandservice=new brandServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取到当前页面，和页面显示条数
        String _currentPage = req.getParameter("currentPage");
        String _pageSize = req.getParameter("pageSize");
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);
        //从前端获取请求体
        BufferedReader br = req.getReader();
        String s = br.readLine();
        Brand brand = JSON.parseObject(s, Brand.class);
        //因为sql语句中需要模糊查询，所以需要给品牌名称，公司名称加上% %
        String brandName = brand.getBrandName();
        String companyName = brand.getCompanyName();//先获取用户填写的要查询的名称条件
        //先做非空判断
        if (brandName!=null&&brandName.length()>0){
            brand.setBrandName("%"+brandName+"%");//如果不为空则加上%符号，为sql语句模糊查询做好准备
        }
        if (companyName!=null&&companyName.length()>0){
            brand.setCompanyName("%"+companyName+"%");//如果不为空则加上%符号，为sql语句模糊查询做好准备
        }
        List<Brand> brands = brandservice.selectByPageAndCondition(currentPage, pageSize, brand);
        int total = brandservice.selectTotalByCondition(brand);
        //封装成一个pageBean对象
        pageBean pagebean=new pageBean();
        pagebean.setRows(brands);
        pagebean.setTotalCount(total);
        //转化为json对象
        String jsonString = JSON.toJSONString(pagebean, SerializerFeature.IgnoreErrorGetter);//解决序列化问题
        resp.setContentType("text/json;charset=utf-8");//设置防止中文乱码
        resp.getWriter().write(jsonString);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
